/*
 * Copyright (c) 2018 PHYTEC Messtechnik GmbH
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <zephyr.h>
#include <device.h>
#include <display/cfb.h>
#include <stdio.h>

#if defined(CONFIG_SSD16XX)
#define DISPLAY_DRIVER		"SSD16XX"
#endif

#if defined(CONFIG_SSD1306)
#define DISPLAY_DRIVER		"SSD1306"
#endif

#ifndef DISPLAY_DRIVER
#define DISPLAY_DRIVER		"DISPLAY"
#endif

static struct device *dev;
static u16_t rows;
static u8_t ppt;

static char fb[1024];

void lvgltest(void);

void distest_init(void)
{
#if defined(CONFIG_DISPLAY)
	u8_t font_width;
	u8_t font_height;

	dev = device_get_binding(DISPLAY_DRIVER);

	if (dev == NULL) {
		printk("Device not found\n");
		return;
	}

	if (display_set_pixel_format(dev, PIXEL_FORMAT_MONO10) != 0) {
		printk("Failed to set required pixel format\n");
		return;
	}

	printk("initialized %s\n", DISPLAY_DRIVER);

	if (cfb_framebuffer_init(dev)) {
		printk("Framebuffer initialization failed!\n");
		return;
	}

	cfb_framebuffer_clear(dev, true);

	display_blanking_off(dev);

	rows = cfb_get_display_parameter(dev, CFB_DISPLAY_ROWS);
	ppt = cfb_get_display_parameter(dev, CFB_DISPLAY_PPT);

	for (int idx = 0; idx < 42; idx++) {
		if (cfb_get_font_size(dev, idx, &font_width, &font_height)) {
			break;
		}
		//cfb_framebuffer_set_font(dev, idx);
		printk("font width %d, font height %d\n",
		       font_width, font_height);
	}

	cfb_framebuffer_set_font(dev, 0);

	printk("x_res %d, y_res %d, ppt %d, rows %d, cols %d\n",
	       cfb_get_display_parameter(dev, CFB_DISPLAY_WIDTH),
	       cfb_get_display_parameter(dev, CFB_DISPLAY_HEIGH),
	       ppt,
	       rows,
	       cfb_get_display_parameter(dev, CFB_DISPLAY_COLS));
#endif

#if 1
	struct display_buffer_descriptor desc;
	
	desc.width = cfb_get_display_parameter(dev, CFB_DISPLAY_WIDTH);
	desc.height = cfb_get_display_parameter(dev, CFB_DISPLAY_HEIGH);
	desc.pitch = desc.width;
	desc.buf_size =  desc.width * desc.height / ppt;
	
	char* fbuffer = display_get_framebuffer(dev);
	printk("FB  %p\n", fbuffer);
	if(fbuffer == NULL){
		fbuffer = fb;
	}

	memset(fbuffer, 0x35, desc.buf_size);
	display_write(dev, 0, 0, &desc ,fbuffer);
#endif

}

void distest_set(char * str){
	display_get_framebuffer(dev);
#if defined(CONFIG_DISPLAY)
    for (int i = 0; i < 8; i++) {
			cfb_framebuffer_clear(dev, false);
			if (cfb_print(dev,
				      "0123456789mMgj!\"§$%&/()=",
				      0, i * ppt)) {
				printk("Failed to print a string\n");
				continue;
			}

			cfb_framebuffer_finalize(dev);
    }
	char  string[64];
	sprintf(string,"Frank %s", str);
	cfb_framebuffer_clear(dev, false);
	cfb_print(dev, string, 0, 0);
	cfb_framebuffer_finalize(dev);
#endif	
}